package cn.wei.reallyenjoy.diary.controller;



import cn.wei.reallyenjoy.common.result.Result;

import cn.wei.reallyenjoy.diary.pojo.vo.DiaryIndexVO;
import cn.wei.reallyenjoy.diary.pojo.vo.WriteDiaryVO;
import cn.wei.reallyenjoy.diary.service.CommentsHystrixService;
import cn.wei.reallyenjoy.diary.service.DiaryService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 日记表 前端控制器
 * </p>
 *
 * @author Wei
 * @since 2021-11-28
 */
@RestController
@Api(tags = "日记管理")
@RequestMapping("/diary")
@RefreshScope
public class DiaryController {

    @Value("${config.info}")
    private String info;

    public static final String COMMENT_SERVICE_URL = "http://COMMENT-SERVICE";

    @Autowired
    private CommentsHystrixService commentsHystrixService;


    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiaryService diaryService;

    @ApiOperation("写日记")
    @PostMapping("/addDiary")
    public Result addDiary(WriteDiaryVO writeDiaryVO){
        diaryService.addDiary(writeDiaryVO);
        return Result.succ(null);
    }

    @ApiOperation("日记列表")
    @GetMapping("/list")
    public Result listAll(){
        List<DiaryIndexVO> list = diaryService.getDiaryList();
        return Result.succ("ok", list);
    }
    @ApiOperation("根据用户id获取日记列表")
    @GetMapping("/getDiaryByUserId/{userId}")
    public Result getDiaryByUserId(@PathVariable("userId") Long userId){

        List<DiaryIndexVO> userDiary = diaryService.getDiaryByUserId(userId);
        return Result.succNoData().succMapData("userDiary",userDiary);
    }

    @ApiOperation("根据用户id获取收藏日记列表")
    @GetMapping("/CollectionByUid/{userId}")
    public Result CollectionByUid(@PathVariable("userId") Long userId){
        List<DiaryIndexVO> userDiary = diaryService.CollectionByUid(userId);
        return Result.succNoData().succMapData("userDiary",userDiary);
    }

    @ApiOperation("根据用户删除日记")
    @DeleteMapping("/deleteDiaryByUidAndDiaryId/{userId}/{diaryId}")
    public Result deleteDiaryByUidAndDiaryId(
            @PathVariable("userId") Long userId,
            @PathVariable("diaryId") Long diaryId){
       int line = diaryService.deleteDiaryByUidAndDiaryId(userId,diaryId);
       if (line>0){
           return Result.succ("删除成功",null);
       }else{
           return Result.succ("删除失败",null);
       }

    }

    @ApiOperation("负载均衡演示：根据日记id获取评论列表")
    @GetMapping("/getCommentsByDiaryId/{diaryId}")
    public Result getCommentsByDiaryId(@PathVariable("diaryId") Long diaryId){
        return restTemplate.getForObject(COMMENT_SERVICE_URL+"/comments/getCommentsByDiaryId/"+diaryId,Result.class);
    }




    @ApiOperation("熔断机制《服务降级》演示：根据日记id获取评论列表")
    @GetMapping("/getCommentsHystrixByDiaryId/{diaryId}")
    public Result getCommentsHystrixByDiaryId(@PathVariable("diaryId") Long diaryId){
        return commentsHystrixService.getCommentsByDiaryId(diaryId);
    }


    //=========服务熔断
    @ApiOperation("熔断机制《服务熔断》演示：根据日记id获取评论列表")
    @HystrixCommand(fallbackMethod = "getCommentsByDiaryIdUserCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
    })
    @GetMapping("/getCommentsByDiaryIdUserCircuitBreaker/{diaryId}")
    public Result getCommentsByDiaryIdUseCircuitBreaker(@PathVariable("diaryId") Long diaryId)
    {
        if(diaryId < 0)
        {
            throw new RuntimeException("******diaryId 不合法");
        }
        String serialNumber = String.valueOf(UUID.randomUUID());

        Result res = commentsHystrixService.getCommentsByDiaryId(diaryId);
        res.setMsg("调用成功，流水号: " + serialNumber);
        return res;
    }
    public Result getCommentsByDiaryIdUserCircuitBreaker_fallback(@PathVariable("diaryId") Long diaryId)
    {
        return Result.fail("diaryId 不合法，请稍后再试，/(ㄒoㄒ)/~~   idiaryId: " +diaryId);
    }


    @ApiOperation("《分布式配置中心》演示：版本信息更换")
    @GetMapping("/getCommentsHystrixByDiaryIdUseConfigCenter/{diaryId}")
    public Result getCommentsHystrixByDiaryIdUseConfigCenter(@PathVariable("diaryId") Long diaryId){
        System.out.println(diaryId);
        Result result = commentsHystrixService.getCommentsByDiaryId(diaryId);
        result.setMsg(info);
        return result;
    }

    @ApiOperation("《分布式服务追踪演示》演示:获取评论列表")
    @GetMapping("/getCommentsHystrixByDiaryIdUseSleuth/{diaryId}")
    public Result getCommentsHystrixByDiaryIdUseSleuth(@PathVariable("diaryId") Long diaryId){
        Result res = commentsHystrixService.getCommentsByDiaryId(diaryId);
        res.setMsg("分布式服务追踪演示,Sleuth,zipkin");
        return res;
    }










}

